/**
 
 * 
 */
package nl.boektrust.btsoep.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

import nl.boektrust.btsoep.shared.model.AvailabilityCode;
import nl.boektrust.btsoep.shared.model.BTEntity;
import nl.boektrust.btsoep.shared.model.Book;
import nl.boektrust.btsoep.shared.model.BookManifestation;
import nl.boektrust.btsoep.shared.model.ContentSpecifier;
import nl.boektrust.btsoep.shared.model.ContentSpecifierType;
import nl.boektrust.btsoep.shared.model.Contributor;
import nl.boektrust.btsoep.shared.model.ContributorRoleCode;
import nl.boektrust.btsoep.shared.model.LanguageCode;
import nl.boektrust.btsoep.shared.model.Person;
import nl.boektrust.btsoep.shared.model.PhysicalBookManifestation;
import nl.boektrust.btsoep.shared.model.Price;
import nl.boektrust.btsoep.shared.model.PriceTypeCode;
import nl.boektrust.btsoep.shared.model.ProductFormCode;
import nl.boektrust.btsoep.shared.model.Supplier;
import nl.boektrust.btsoep.shared.model.SupplyDetail;
import nl.boektrust.btsoep.shared.model.TextType;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.*;


import com.google.appengine.repackaged.com.google.protobuf.TextFormat.ParseException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.ObjectifyService;

/**
 * @author rao3
 *
 * the implementation of the server that can serve XML requests to Koppelvlak bookstores. 
 */
public class DatabaseRunner extends HttpServlet {
	private boolean isObjectifyServiceRegistered = false;
	private ServletContext context;

	
	ServletContext getContext() {
		return this.context;
	}

	public void init() throws ServletException {
		context = getServletContext();
		//System.err.println("Real Path = " + context.getRealPath("/"));
	}

	/**
	 * 
	 */
	public DatabaseRunner() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param delegate
	 */
	public DatabaseRunner(Object delegate) {
		//super(delegate);
		// TODO Auto-generated constructor stub
	}
	
	private void registerServices () {
		if (isObjectifyServiceRegistered == false) {

			ObjectifyService.register(BTEntity.class);
			ObjectifyService.register(Person.class);
			ObjectifyService.register(PhysicalBookManifestation.class);
			ObjectifyService.register(BookManifestation.class);
			ObjectifyService.register(Book.class);
			isObjectifyServiceRegistered = true;
		}
	}
	
	public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException  
	{
		
		/*
		 * get raw XML from the inputstream. 
		 */
		
		System.err.println("databaserunner:doPost");

	} 
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		System.err.println("databaserunner:doGet");
		List<PhysicalBookManifestation> books = null;
		int numEntities = new PersistentServiceImpl().numPhysicalBookManifestations();
		Queue queue = QueueFactory.getDefaultQueue();
		try {
			for (int i=0; i<numEntities/500; i++) {
			    queue.add(withUrl("/chunktask").param("key", new Integer(i).toString()));

			}
		}  catch (com.google.apphosting.api.DeadlineExceededException e) {
			System.err.println("Error retrieving books: DeadlineExceededException");

		}
		if (books != null) {
			System.err.println("retrieved "+books.size()+" PhysicalBookManifestation objects");
			for (PhysicalBookManifestation b : books) {
				System.err.print(b.getRecordReference());
				System.err.print(" ");
				new PersistentServiceImpl().deletePhysicalBookManifestation(b);
				new PersistentServiceImpl().persistPhysicalBookManifestation(b);
			}
			System.err.println("");
		}
		System.err.println("databaserunner:doGet finished");
		
	}


}
